package com.jusfoun.communication.listener;

import com.jusfoun.communication.service.MessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * 消息监听器
 *
 * @author player six
 * @email jslcylcy@163.com
 * @create 2017-10-16 15:01
 **/
@Component
public class MessageListener {

    @Autowired
    private MessageService messageService;

    private Thread thread;

    /**
     * 控制消息监听线程是否继续运行
     */
    private volatile boolean isRunning = true;

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageListener.class);

    /**
     * 监听消息队列,处理待发送的消息
     */
    @PostConstruct
    public void messageListener() {
        thread = new Thread(() -> {
            while (isRunning) {
                messageService.dealMsg2Send();
            }
        }, "消息监听任务线程");
        thread.start();
    }

    @PreDestroy
    public void stop() {
        isRunning = false;
        int count = 0;
        LOGGER.info("等待线程停止");
        try {
            while (thread.isAlive() && count < 75) {
                Thread.sleep(1000);
                count++;
            }
            LOGGER.info("线程停止，count:" + count);
        } catch (InterruptedException e) {
            LOGGER.error("停止线程出错", e);
            Thread.currentThread().interrupted();
        }

        if (thread != null && thread.isAlive()) {
            LOGGER.info("线程未停止，需要手动打断");
            thread.interrupt();
        }
    }

}
